<?php

namespace app\proxy\controller\employ;

use app\proxy\controller\Controller;
use app\proxy\model\employ\Poster as PosterModel;

class Poster extends Controller
{
    /**
     * 福利官列表
     */
    public function index()
    {
        // 供应商列表
        $model = new PosterModel;
        $list = $model->getList($this->postData(), $this->getRegionIds(), $this->getProxyId());
        return $this->renderSuccess('', compact('list'));
    }

    public function add()
    {
        $model = new PosterModel;
        $data = $this->postData();
        // 新增记录
        $data["proxy_id"] = $this->getProxyId();
        if ($model->add($data)) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 编辑供应商
     */
    public function edit($poster_id)
    {
        $model = PosterModel::detail($poster_id, ['bg_image', 'qr_code']);
        if ($this->request->isGet()) {
            $model["region_id"] = [$model["province_id"], $model["city_id"]];
            return $this->renderSuccess('', compact('model'));
        }
        $data = $this->postData();
        // 新增记录
        $data["proxy_id"] = $this->getProxyId();
        if ($model->edit($data, $this->getProxyId())) {
            return $this->renderSuccess('', '更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    public function publish($poster_id)
    {
        $model = PosterModel::detail($poster_id);
        if (!$model || $model["is_audit"] != 1) {
            return $this->renderError('记录不存在或未通过审核');
        }
        $data = [];
        // 新增记录
        $data["publish_status"] = 1;
        if ($model->save($data)) {
            (new PosterModel)->where("poster_id", "<>", $poster_id)
                ->where("province_id", $model['province_id'])
                ->where("city_id", $model['province_id'])
                ->update(["publish_status" => 0]);
            return $this->renderSuccess('发布成功');
        }
        return $this->renderError($model->getError() ?: '发布失败');
    }
}